<!DOCTYPE html>
<html lang="zh-cn">
    <head>
        <meta charset="UTF-8"/>
        <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <title>模板字面量-带标签的模板字面量</title>
    </head>
    <body>
        <h1>模板字面量-带标签的模板字面量</h1>
        <p>来源:<a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/template_strings">https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/template_strings</a></p>
        <h3>带标签的模板字面量</h3>
        <script>
            // 案例一：标签函数返回字符串
            // var person = 'Mike';
            // var age = 28;

            // function myTag(strings, personExp, ageExp) {

            //   var str0 = strings[0]; // "that "
            //   var str1 = strings[1]; // " is a "

            //   // There is technically a string after
            //   // the final expression (in our example),
            //   // but it is empty (""), so disregard.
            //   // var str2 = strings[2];

            //   var ageStr;
            //   if (ageExp > 99){
            //     ageStr = 'centenarian';
            //   } else {
            //     ageStr = 'youngster';
            //   }

            //   return str0 + personExp + str1 + ageStr;

            // }

            // var output = myTag`that ${ person } is a ${ age }`;

            // console.log(output);
            // 案例二：标签函数不一定返回字符串
            function template(strings, ...keys) {
              return (function(...values) {
                var dict = values[values.length - 1] || {};
                var result = [strings[0]];
                keys.forEach(function(key, i) {
                  var value = Number.isInteger(key) ? values[key] : dict[key];
                  result.push(value, strings[i + 1]);
                });
                return result.join('');
              });
            }

            var t1Closure = template`${0}${1}${0}!`;
            t1Closure('Y', 'A');  // "YAY!" 
            var t2Closure = template`${0} ${'foo'}!`;
            t2Closure('Hello', {foo: 'World'});  // "Hello World!"
        </script>
    </body>
</html>